package com.gymmsystem.GYMMSystem.config;

import com.gymmsystem.GYMMSystem.entity.Announcement;
import com.gymmsystem.GYMMSystem.mapper.AnnouncementMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class AnnouncementPublishTask {

    @Autowired
    private AnnouncementMapper announcementMapper;

    /**
     * 每分钟执行一次，检查需要发布的预约公告
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    @Transactional
    public void publishScheduledAnnouncements() {
        try {
            LocalDateTime now = LocalDateTime.now();
            log.info("开始检查预约发布的公告，当前时间: {}", now);

            // 查询状态为草稿(0)且预约发布时间小于等于当前时间的公告
            List<Announcement> announcementsToPublish = announcementMapper
                    .selectScheduledAnnouncements(now);

            if (announcementsToPublish.isEmpty()) {
                log.info("没有需要发布的预约公告");
                return;
            }

            for (Announcement announcement : announcementsToPublish) {
                // 更新状态为已发布(1)
                announcement.setStatus(1);
                announcement.setUpdatedAt(LocalDateTime.now());
                announcementMapper.updateById(announcement);

                log.info("成功发布预约公告: ID={}, 标题={}",
                        announcement.getId(), announcement.getTitle());
            }

            log.info("完成发布 {} 个预约公告", announcementsToPublish.size());

        } catch (Exception e) {
            log.error("发布预约公告时发生错误", e);
        }
    }
}